import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'

const state = {
  token: getToken(),
  userInfo: {} // 这里有一个空对象，为了放置后面取数据报错
}

const mutations = {
  setToken(state, token) {
    // 将token存到vuex中(vuex中的数据在内存中，刷新会消失)
    state.token = token
    // 将token存储到cookie缓存中
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state, data) {
    state.userInfo = data
  }
}

const actions = {
  async login(context, data) {
    // 1. 发生登录请求 TODO
    // console.log(data)
    // // 2. 获取token
    const res = await login(data)
    // 3. 提交mutation
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    // console.log(res)
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo', {})
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
